package com.zzw.zim.common.utils;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>项目名称: zzw-tech </p>
 * <p>包名称: com.zzw.bridge.common.utils </p>
 * <p>描述: JSON工具类 </p>
 * <p> JSON工具类 </p>
 * <p>创建时间: 2022/11/14 17 </p>
 *
 * @author coco
 * @version v1.0
 */
@Component
public class JsonUtils {
	private static ObjectMapper obm;

	public static String toJsonString (Object object) {
		try {
			return obm.writeValueAsString(object);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public static <T> T parseObject (String text, Class<T> clazz) {
		if (StrUtil.isEmpty(text)) {
			return null;
		}
		try {
			return obm.readValue(text, clazz);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public static <T> T parseObject (byte[] bytes, Class<T> clazz) {
		if (ArrayUtil.isEmpty(bytes)) {
			return null;
		}
		try {
			return obm.readValue(bytes, clazz);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public static <T> T parseObject (String text, cn.hutool.core.lang.TypeReference<T> reference) {
		if (StrUtil.isEmpty(text)) {
			return null;
		}
		return JSONUtil.toBean(text, reference, true);
	}

	public static <T> T parseObject (String text, TypeReference<T> typeReference) {
		try {
			return obm.readValue(text, typeReference);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public static <T> List<T> parseArray (String text, Class<T> clazz) {
		if (StrUtil.isEmpty(text)) {
			return new ArrayList<>();
		}
		try {
			return obm.readValue(text, obm.getTypeFactory().constructCollectionType(List.class, clazz));
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	@Autowired
	public void setObm (ObjectMapper obm) {
		JsonUtils.obm = obm;
		obm.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
	}

}
